package com.car.rental.user.controller;

import com.car.rental.common.core.response.ResponseResult;
import com.car.rental.user.model.request.UpdateUserRequest;
import com.car.rental.user.model.response.UserInfoResponse;
import com.car.rental.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.car.rental.common.core.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.car.rental.common.core.response.PageResult;
import com.car.rental.user.model.request.UserSearchRequest;
import com.car.rental.common.utils.JwtUtils;
import com.car.rental.user.model.request.UpdateStatusRequest;
import org.springframework.web.multipart.MultipartFile;
import com.car.rental.user.model.request.UpdatePasswordRequest;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.List;

@Validated
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final JwtUtils jwtUtils;
    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/current")
    public ResponseResult<UserInfoResponse> getCurrentUserInfo(@RequestHeader("Authorization") String token) {
        return userService.getCurrentUserInfo(token);
    }

    /**
     * 更新用户基本信息
     */
    @PutMapping("/{userId}")
    public ResponseResult<Void> updateUserInfo(
            @PathVariable Long userId,
            @Valid @RequestBody UpdateUserRequest request) {
        return userService.updateUserInfo(userId, request);
    }

    /**
     * 更新用户头像
     */
    @PostMapping("/avatar")
    public ResponseResult<String> updateAvatar(
            @RequestHeader("Authorization") String token,
            @RequestParam("file") MultipartFile file) {
        Long userId = jwtUtils.getUserIdFromToken(token.substring(7));
        return userService.updateAvatar(userId, file);
    }

    /**
     * 更新用户手机号
     */
    @PutMapping("/{userId}/phone")
    public ResponseResult<Void> updatePhone(
            @PathVariable Long userId,
            @NotBlank(message = "手机号不能为空")
            @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
            @RequestParam String phone) {
        return userService.updatePhone(userId, phone);
    }

    /**
     * 更新用户邮箱
     */
    @PutMapping("/{userId}/email")
    public ResponseResult<Void> updateEmail(
            @PathVariable Long userId,
            @NotBlank(message = "邮箱不能为空")
            @Pattern(regexp = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$", message = "邮箱格式不正确")
            @RequestParam String email) {
        return userService.updateEmail(userId, email);
    }

    /**
     * 更新用户昵称
     */
    @PutMapping("/{userId}/nickname")
    public ResponseResult<Void> updateNickname(
            @PathVariable Long userId,
            @NotBlank(message = "昵称不能为空")
            @RequestParam String nickname) {
        return userService.updateNickname(userId, nickname);
    }

    /**
     * 更新用户状态（超级管理员接口）
     */
    @PutMapping("/{userId}/status")
    public ResponseResult<Void> updateStatus(
            @RequestHeader("Authorization") String token,
            @PathVariable Long userId,
            @RequestBody UpdateStatusRequest request) {
        // 验证是否是超级管理员
        Long currentUserId = jwtUtils.getUserIdFromToken(token.substring(7));
        if (!userService.checkSuperAdminRole(currentUserId)) {
            throw new BusinessException("需要超级管理员权限");
        }
        return userService.updateStatus(userId, request.getStatus());
    }

    /**
     * 搜索用户（超级管理员接口）
     */
    @GetMapping("/search")
    public ResponseResult<PageResult<UserInfoResponse>> searchUsers(
            @Valid UserSearchRequest request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long currentUserId = (Long) authentication.getPrincipal();
        if (!userService.checkSuperAdminRole(currentUserId)) {
            throw new BusinessException("需要超级管理员权限");
        }
        return userService.searchUsers(request);

    }

    /**
     * 分配用户角色（超级管理员接口）
     */
    @PostMapping("/{userId}/role/{roleId}")
    public ResponseResult<Void> assignRole(
            @PathVariable Long userId,
            @PathVariable Long roleId) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long currentUserId = (Long) authentication.getPrincipal();
        if (!userService.checkSuperAdminRole(currentUserId)) {
            throw new BusinessException("需要超级管理员权限");
        }
        return userService.assignRole(userId, roleId);
    }

    /**
     * 更新用户角色
     */
    @PutMapping("/{userId}/role/{roleId}")
    public ResponseResult<Void> updateUserRole(
            @RequestHeader("Authorization") String token,
            @PathVariable Long userId,
            @PathVariable Long roleId) {
        // 验证是否是超级管理员
        Long currentUserId = jwtUtils.getUserIdFromToken(token.substring(7));
        if (!userService.checkSuperAdminRole(currentUserId)) {
            throw new BusinessException("需要超级管理员权限");
        }
        return userService.updateUserRole(userId, roleId);
    }

    /**
     * 验证用户是否有权限操作
     */
    private void validatePermission(String token, Long userId) {
        // 从token中获取用户ID，验证是否为当前用户
        if (!userService.validatePermission(token, userId)) {
            throw new BusinessException("无权操作");
        }
    }

    /**
     * 获取所有用户列表（超级管理员接口）
     */
    @GetMapping("/list")
    public ResponseResult<List<UserInfoResponse>> getAllUsers(
            @RequestHeader("Authorization") String token) {
        // 验证是否是超级管理员
        Long currentUserId = jwtUtils.getUserIdFromToken(token.substring(7));
        if (!userService.checkSuperAdminRole(currentUserId)) {
            throw new BusinessException("需要超级管理员权限");
        }
        return userService.getAllUsers();
    }

    /**
     * 修改密码
     */
    @PutMapping("/{userId}/password")
    public ResponseResult<Void> updatePassword(
            @RequestHeader("Authorization") String token,
            @PathVariable Long userId,
            @Valid @RequestBody UpdatePasswordRequest request) {
        log.info("收到修改密码请求: userId={}", userId);
        validatePermission(token, userId);
        return userService.updatePassword(userId, request);
    }
} 